package nk;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * NC58 找到搜索二叉树中两个错误的节点
 */
public class NK58_FindError {

    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param root TreeNode类 the root
     * @return int整型一维数组
     */
    public static int[] findError(TreeNode root) {
        // write code here
        int[] ans = new int[2];
        List<Integer> list = new ArrayList<>();
        order(root, list);
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i) >= list.get(i + 1)) {
                ans[1] = list.get(i);
                break;
            }
        }
        for (int i = list.size() - 1; i >= 1; i--) {
            if (list.get(i - 1) >= list.get(i)) {
                ans[0] = list.get(i);
                break;
            }
        }
        return ans;
    }

    public static void order(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        order(node.left, list);
        list.add(node.val);
        order(node.right, list);

    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.right = new TreeNode(3);
        int[] error = findError(treeNode);
        System.out.println(Arrays.toString(error));
    }
}
